package com.imcrl.core.state
{
	import flash.utils.Dictionary;
	
	public class StateMachine
	{
		protected var states:Dictionary;
		
		protected var currentState:IState;
		public function StateMachine()
		{
			states=new Dictionary();
		}
		
		
		public function add(state:IState):void{
			states[state.name]=state;
			state.machine=this;
		}
		
		public function remove(name:String):IState{
			var state:IState=states[name];
			
			if(state){
				state[name]=null;
				delete state[name];
			}
			return state;
		}
		
		/**
		 * 取得状态; 
		 * @param name
		 * @return 
		 * 
		 */		
		public function getState(name:String):IState{
			return states[name];
		}
		
		
		public function set state(name:String):void{
			var state:IState=states[name];
			
			if(currentState){
				currentState.end();
			}
			currentState=state;
			if(currentState){
				if(currentState.initialized==false)currentState.initialize();
				currentState.start();
			}
		}
		
		public function get state():String{
			return currentState.name;
		}
		
	}
}